package com.ydzh.kfqgwvisitor.aspect;

import cn.hutool.core.util.StrUtil;
import com.ydzh.kfqgwvisitor.annotation.SysLog;
import com.ydzh.kfqgwvisitor.entity.RequestLog;
import com.ydzh.kfqgwvisitor.service.RequestLogService;
import com.ydzh.kfqgwvisitor.util.CommonUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author zcj
 * @description
 * @date 2021/12/2021/12/13
 **/
@Component
@Aspect
@Slf4j
public class RequestRecordAspect {
    @Autowired
    private RequestLogService requestLogService;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    /*@Pointcut("execution(* com.ydzh.kfqgwvisitor.controller.*.*(..))")
    public void pointCut() {
    }*/

    @Before("@annotation(sysLog)")
    public void before(JoinPoint joinPoint, SysLog sysLog) {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String userAgent = request.getHeader("user-agent");
        String ipAddr = CommonUtil.getIpAddr(request);
        RequestLog requestLog = new RequestLog(userAgent, request.getRequestURL().toString(), request.getMethod(), ipAddr, LocalDateTime.now());
        String controllerDescription = "";
        Api api = joinPoint.getTarget().getClass().getAnnotation(Api.class);
        if (api != null) {
            String[] tags = api.tags();
            if (tags != null && tags.length > 0) {
                controllerDescription = tags[0];
            }
        }

        String controllerMethodDescription = sysLog.value();
        if (StrUtil.isEmpty(controllerDescription)) {
            requestLog.setDescription(controllerMethodDescription);
        } else {
            requestLog.setDescription(controllerDescription + "-" + controllerMethodDescription);
        }
        threadPoolTaskExecutor.execute(() -> requestLogService.save(requestLog));

    }
}
